package com.jijs.soap.client.handler;

import java.io.IOException;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.w3c.dom.Node;

public class HeaderHandler implements SOAPHandler<SOAPMessageContext>{

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		try{
			String ns = "http://www.infcn.com.cn/";
			Boolean out = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
			if(out){
				SOAPMessage message = context.getMessage();
				SOAPEnvelope enve = message.getSOAPPart().getEnvelope();
				
				SOAPBody body = enve.getBody();
				Node node = body.getChildNodes().item(0);
				String pn = node.getLocalName();
				if("list".equals(pn) || "addUser".equals(pn)){
					SOAPHeader header = enve.getHeader();
					if(header==null){
						header = enve.addHeader();
					}
					QName qname = new QName(ns, "licenseInfo", "ns");
					header.addHeaderElement(qname).setValue("123123");
					message.writeTo(System.out);
				}
			}
		} catch(SOAPException e){
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		System.out.println("error");
		return false;
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}
	

}
